<script setup>
import { ref, computed, watch } from 'vue';
import { getCountries, getCountryCallingCode, parsePhoneNumberFromString } from 'libphonenumber-js';

const props = defineProps({
  initialPhoneNumber: {
    type: String,
    default: ''
  },
  initialCountryCode: {
    type: String,
    default: '+1'
  },
  placeholder: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['update:phoneData']);

// Country data
const primaryCountryMap = {
  '+1': 'US',    // United States
  '+44': 'GB',   // United Kingdom
  '+81': 'JP',   // Japan
  '+82': 'KR',   // South Korea
  '+65': 'SG',   // Singapore
  '+61': 'AU',   // Australia
  '+91': 'IN',   // India
  '+60': 'MY',   // Malaysia
};

// Country name mapping
const countryNameMap = {
  'AF': 'Afghanistan',
  'AL': 'Albania',
  'DZ': 'Algeria',
  'AO': 'Angola',
  'AI': 'Anguilla',
  'AG': 'Antigua and Barbuda',
  'AR': 'Argentina',
  'AM': 'Armenia',
  'AW': 'Aruba',
  'AZ': 'Azerbaijan',
  'BS': 'Bahamas',
  'BH': 'Bahrain',
  'BD': 'Bangladesh',
  'BB': 'Barbados',
  'BY': 'Belarus',
  'BZ': 'Belize',
  'BJ': 'Benin',
  'BM': 'Bermuda',
  'BT': 'Bhutan',
  'BO': 'Bolivia',
  'BQ': 'Bonaire, Sint Eustatius and Saba',
  'BA': 'Bosnia and Herzegovina',
  'BW': 'Botswana',
  'BR': 'Brazil', // 已有
  'IO': 'British Indian Ocean Territory',
  'BN': 'Brunei Darussalam',
  'BF': 'Burkina Faso',
  'BI': 'Burundi',
  'KH': 'Cambodia',
  'CM': 'Cameroon',
  'CV': 'Cabo Verde',
  'KY': 'Cayman Islands',
  'CF': 'Central African Republic',
  'TD': 'Chad',
  'CL': 'Chile',
  'CN': 'China',
  'CO': 'Colombia',
  'KM': 'Comoros',
  'CG': 'Congo',
  'CD': 'Congo, Democratic Republic of the',
  'CK': 'Cook Islands',
  'CR': 'Costa Rica',
  'CI': 'Côte d\'Ivoire',
  'HR': 'Croatia', // 已有
  'CU': 'Cuba',
  'CW': 'Curaçao',
  'CY': 'Cyprus', // 已有
  'CZ': 'Czechia', // 已有 ('Czech Republic')
  'DJ': 'Djibouti',
  'DM': 'Dominica',
  'DO': 'Dominican Republic',
  'TL': 'East Timor (Timor-Leste)',
  'EC': 'Ecuador',
  'EG': 'Egypt',
  'SV': 'El Salvador',
  'GQ': 'Equatorial Guinea',
  'ER': 'Eritrea',
  'EE': 'Estonia', // 已有
  'SZ': 'Eswatini',
  'ET': 'Ethiopia',
  'FK': 'Falkland Islands (Malvinas)',
  'FO': 'Faroe Islands',
  'FJ': 'Fiji',
  'FI': 'Finland', // 已有
  'GF': 'French Guiana',
  'PF': 'French Polynesia',
  'TF': 'French Southern Territories',
  'GA': 'Gabon',
  'GM': 'Gambia',
  'GE': 'Georgia',
  'DE': 'Germany', // 已有
  'GH': 'Ghana',
  'GI': 'Gibraltar',
  'GR': 'Greece', // 已有
  'GL': 'Greenland',
  'GD': 'Grenada',
  'GP': 'Guadeloupe',
  'GU': 'Guam',
  'GT': 'Guatemala',
  'GG': 'Guernsey',
  'GN': 'Guinea',
  'GW': 'Guinea-Bissau',
  'GY': 'Guyana',
  'HT': 'Haiti',
  'HN': 'Honduras',
  'HK': 'Hong Kong',
  'HU': 'Hungary', // 已有
  'IS': 'Iceland', // 已有
  'IN': 'India', // 已有
  'ID': 'Indonesia', // 已有
  'IR': 'Iran, Islamic Republic of',
  'IQ': 'Iraq',
  'IE': 'Ireland', // 已有
  'IM': 'Isle of Man',
  'IL': 'Israel',
  'IT': 'Italy', // 已有
  'JM': 'Jamaica',
  'JP': 'Japan', // 已有
  'JE': 'Jersey',
  'JO': 'Jordan',
  'KZ': 'Kazakhstan',
  'KE': 'Kenya',
  'KI': 'Kiribati',
  'KP': 'Korea, Democratic People\'s Republic of',
  'XK': 'Kosovo',
  'KW': 'Kuwait',
  'KG': 'Kyrgyzstan',
  'LA': 'Lao People\'s Democratic Republic',
  'LV': 'Latvia', // 已有
  'LB': 'Lebanon',
  'LS': 'Lesotho',
  'LR': 'Liberia',
  'LY': 'Libya',
  'LI': 'Liechtenstein',
  'LT': 'Lithuania', // 已有
  'LU': 'Luxembourg', // 已有
  'MO': 'Macao',
  'MG': 'Madagascar',
  'MW': 'Malawi',
  'MV': 'Maldives',
  'ML': 'Mali',
  'MT': 'Malta', // 已有
  'MH': 'Marshall Islands',
  'MQ': 'Martinique',
  'MR': 'Mauritania',
  'MU': 'Mauritius',
  'YT': 'Mayotte',
  'MX': 'Mexico', // 已有
  'FM': 'Micronesia, Federated States of',
  'MD': 'Moldova, Republic of',
  'MC': 'Monaco',
  'MN': 'Mongolia',
  'ME': 'Montenegro',
  'MS': 'Montserrat',
  'MA': 'Morocco',
  'MZ': 'Mozambique',
  'MM': 'Myanmar (Burma)',
  'NA': 'Namibia',
  'NR': 'Nauru',
  'NP': 'Nepal',
  'NL': 'Netherlands', // 已有
  'NC': 'New Caledonia',
  'NZ': 'New Zealand', // 已有
  'NI': 'Nicaragua',
  'NE': 'Niger',
  'NG': 'Nigeria',
  'NU': 'Niue',
  'NF': 'Norfolk Island',
  'MP': 'Northern Mariana Islands',
  'NO': 'Norway', // 已有
  'OM': 'Oman',
  'PK': 'Pakistan',
  'PW': 'Palau',
  'PS': 'Palestine, State of',
  'PA': 'Panama',
  'PG': 'Papua New Guinea',
  'PY': 'Paraguay',
  'PE': 'Peru',
  'PH': 'Philippines', // 已有
  'PN': 'Pitcairn',
  'PL': 'Poland', // 已有
  'PT': 'Portugal', // 已有
  'PR': 'Puerto Rico',
  'QA': 'Qatar',
  'RE': 'Réunion',
  'RO': 'Romania', // 已有
  'RU': 'Russia', // 已有
  'RW': 'Rwanda',
  'BL': 'Saint Barthélemy',
  'SH': 'Saint Helena, Ascension and Tristan da Cunha',
  'KN': 'Saint Kitts and Nevis',
  'LC': 'Saint Lucia',
  'MF': 'Saint Martin (French part)',
  'SX': 'Sint Maarten (Dutch part)',
  'VC': 'Saint Vincent and the Grenadines',
  'WS': 'Samoa',
  'SM': 'San Marino',
  'ST': 'Sao Tome and Principe',
  'SA': 'Saudi Arabia', // 已有
  'SN': 'Senegal',
  'RS': 'Serbia',
  'SC': 'Seychelles',
  'SL': 'Sierra Leone',
  'SG': 'Singapore', // 已有
  'SX': 'Sint Maarten',
  'SK': 'Slovakia', // 已有
  'SI': 'Slovenia', // 已有
  'SB': 'Solomon Islands',
  'SO': 'Somalia',
  'ZA': 'South Africa', // 已有
  'GS': 'South Georgia and the South Sandwich Islands',
  'SS': 'South Sudan',
  'LK': 'Sri Lanka',
  'SD': 'Sudan',
  'SR': 'Suriname',
  'SJ': 'Svalbard and Jan Mayen',
  'SE': 'Sweden', // 已有
  'CH': 'Switzerland', // 已有
  'SY': 'Syrian Arab Republic',
  'TW': 'Taiwan, Province of China',
  'TJ': 'Tajikistan',
  'TZ': 'Tanzania, United Republic of',
  'TH': 'Thailand', // 已有
  'TG': 'Togo',
  'TK': 'Tokelau',
  'TO': 'Tonga',
  'TT': 'Trinidad and Tobago',
  'TN': 'Tunisia',
  'TR': 'Turkey', // 已有
  'TM': 'Turkmenistan',
  'TC': 'Turks and Caicos Islands',
  'TV': 'Tuvalu',
  'UG': 'Uganda',
  'UA': 'Ukraine',
  'AE': 'United Arab Emirates', // 已有
  'GB': 'United Kingdom', // 已有
  'US': 'United States', // 已有
  'UM': 'United States Minor Outlying Islands',
  'UY': 'Uruguay',
  'UZ': 'Uzbekistan',
  'VU': 'Vanuatu',
  'VE': 'Venezuela',
  'VN': 'Vietnam', // 已有
  'VG': 'Virgin Islands (British)',
  'VI': 'Virgin Islands (U.S.)',
  'WF': 'Wallis and Futuna',
  'EH': 'Western Sahara',
  'YE': 'Yemen',
  'ZM': 'Zambia',
  'ZW': 'Zimbabwe'
};

// Generate unique ID for each country
const generateUniqueId = (country) => `${country.label}_${country.value}`;

// Create countries list
const countries = getCountries()
  .filter(iso2 => iso2 !== 'CN')
  .map((iso2) => {
    const code = `+${getCountryCallingCode(iso2)}`;
    const country = {
      label: iso2,
      value: code,
      // displayName: new Intl.DisplayNames(['en'], { type: 'region' }).of(iso2),
      displayName: countryNameMap[iso2] || iso2,
      isPrimary: primaryCountryMap[code] === iso2
    };
    country.uniqueId = generateUniqueId(country);
    country.searchKeys = [
      country.displayName.toLowerCase(),
      country.label.toLowerCase(),
      country.value.toLowerCase(),
      country.value.substring(1)
    ];
    return country;
  })
  .sort((a, b) => {
    if (a.isPrimary && !b.isPrimary) return -1;
    if (!a.isPrimary && b.isPrimary) return 1;
    return a.displayName.localeCompare(b.displayName);
  });

// Component state
const phoneNumber = ref(props.initialPhoneNumber);
const selectedCountry = ref(countries.find(c => c.value === props.initialCountryCode) || countries[0]);
const searchQuery = ref('');
const countryPopup = ref(null);

// Computed
const filteredCountries = computed(() => {
  const query = searchQuery.value.toLowerCase().trim();
  if (!query) return countries;

  return countries.filter(country =>
    country.searchKeys.some(key => key.includes(query))
  );
});

// Methods
const getOptimizedFlagUrl = (countryCode) => {
  if (!countryCode) return '';
  return `https://flagcdn.com/20x15/${countryCode.toLowerCase()}.png`;
};

const showCountryPicker = () => {
  countryPopup.value?.open();
};

const selectCountry = (country) => {
  selectedCountry.value = country;
  countryPopup.value?.close();
  validateAndEmit();
};

const handleSearch = () => {
  // Search is handled by computed filteredCountries
};

const handlePhoneInput = () => {
  validateAndEmit();
};

const validateAndEmit = () => {
  //需要先放入定时器，否则第一次加载fullNumber拿不到数据
  setTimeout(()=>{
    const fullNumber = `${selectedCountry.value.value} ${phoneNumber.value}`;
    let isValid = false;

    try {
      const parsedNumber = parsePhoneNumberFromString(fullNumber);
      isValid = parsedNumber?.isValid() || false;
    } catch (error) {
      console.error('Phone validation error:', error);
    }

    emit('update:phoneData', {
      isValid,
      data: {
        countryCode: selectedCountry.value.value,
        phoneNumber: phoneNumber.value,
        fullNumber,
        countryInfo: selectedCountry.value
      }
    });
  })
};

// Watch for prop changes
watch(() => props.initialPhoneNumber, (newValue) => {
  if (newValue !== undefined) {
    phoneNumber.value = newValue;
    validateAndEmit();
  }
});

watch(() => props.initialCountryCode, (newValue) => {
  if (newValue) {
    const country = countries.find(c => c.value === newValue);
    if (country) {
      selectedCountry.value = country;
      validateAndEmit();
    }
  }
});
</script>
<template>
  <view class="phone-input-container">
    <view class="phone-input-wrapper">
      <!-- Country Code Selector -->
      <view class="country-selector" @tap="showCountryPicker">
        <image
          :src="getOptimizedFlagUrl(selectedCountry.label)"
          class="country-flag"
          mode="aspectFit"
        />
        <text class="country-code">{{ selectedCountry.value }}</text>
        <uni-icons type="bottom" size="12" color="#666"></uni-icons>
      </view>

      <!-- Phone Number Input -->
      <uni-easyinput
        class="phone-number-input"
        v-model.trim="phoneNumber"
        :placeholder="placeholder || 'Enter phone number'"
        type="number"
        @input="handlePhoneInput"
      />
    </view>

    <!-- Country Picker Popup -->
    <uni-popup ref="countryPopup" type="bottom">
      <view class="country-picker">
        <view class="picker-header">
          <view class="search-box">
            <uni-easyinput
              v-model="searchQuery"
              placeholder="Search country"
              @input="handleSearch"
            />
          </view>
        </view>
        <scroll-view scroll-y class="country-list">
          <view
            v-for="country in filteredCountries"
            :key="country.uniqueId"
            class="country-item"
            @tap="selectCountry(country)"
          >
            <image
              :src="getOptimizedFlagUrl(country.label)"
              class="country-flag"
              mode="aspectFit"
            />
            <text class="country-name">{{ country.displayName }}</text>
            <text class="country-code">{{ country.value }}</text>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>
<style  scoped>
.phone-input-container {
  width: 100%;
}

.phone-input-wrapper {
  display: flex;
  align-items: center;
  width: 100%;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.country-selector {
  display: flex;
  align-items: center;
  padding: 0 10px;
  border-right: 1px solid #dcdfe6;
  height: 44px;
  background-color: #f5f7fa;
}

.country-flag {
  width: 20px;
  height: 15px;
  margin-right: 5px;
  border-radius: 2px;
}

.country-code {
  margin: 0 5px;
  color: #333;
  font-size: 14px;
}

.phone-number-input {
  flex: 1;
}

/* Country Picker Styles */
.country-picker {
  background-color: #fff;
  border-radius: 10px 10px 0 0;
  max-height: 60vh;
  display: flex;
  flex-direction: column;
}

.picker-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.search-box {
  margin-bottom: 10px;
}

.country-list {
  flex: 1;
  height: 60vh;
  overflow: auto;
}

.country-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.country-name {
  flex: 1;
  margin: 0 10px;
  font-size: 14px;
  color: #333;
}

/* Override uni-easyinput default styles */
:deep(.uni-easyinput__content) {
  border: none !important;
  background-color: transparent !important;
  height: 44px !important;
}

:deep(.uni-easyinput__content-input) {
  height: 44px !important;
  padding: 0 10px !important;
}

:deep(.uni-forms-item__content) {
  border: none !important;
}

:deep(.uni-forms-item) {
  padding: 0 !important;
}
</style>

<!--
使用说明:

1. 引入组件:
   import PhoneNumberInput from '@/components/PhoneNumberInput.vue';

2. 在父组件中注册:
   components: {
     PhoneNumberInput
   }

3. 在模板中使用:
   <PhoneNumberInput
     :initialPhoneNumber="phoneNumber"
     :initialCountryCode="countryCode"
     @update:phoneData="handlePhoneData"
   />

4. 参数说明:
   - initialPhoneNumber: 初始电话号码，不包含国家代码 (String, 默认: '')
   - initialCountryCode: 初始国家代码，如 '+1' (String, 默认: '+1')

5. 事件:
   - update:phoneData: 当电话号码变更时触发，返回对象:
     {
       isValid: Boolean, // 电话号码是否有效
       data: {
         countryCode: String, // 国家代码 (如 '+1')
         phoneNumber: String, // 不带国家代码的电话号码
         fullNumber: String,  // 完整电话号码 (国家代码+电话号码)
         isValid: Boolean     // 电话号码是否有效
       }
     }

6. 使用示例:
   <template>
     <PhoneNumberInput
       :initialPhoneNumber="form.phoneNumber"
       :initialCountryCode="form.countryCode"
       @update:phoneData="handlePhoneData"
     />
   </template>

   <script setup>
   import PhoneNumberInput from '@/components/PhoneNumberInput.vue';

   const form = ref({
     phoneNumber: '',
     countryCode: '+1'
   });

   const handlePhoneData = (phoneData) => {
     if (phoneData.isValid) {
       // 处理有效的电话号码
       form.value.phone = phoneData.data.fullNumber;
     } else {
       // 处理无效的电话号码
       console.log('无效的电话号码');
     }
   };
   </script>
-->
